import uuid
from http import server

from PIL import Image, ImageFont
from PIL.ImageDraw import ImageDraw
from django.urls import reverse
from django.utils.six import BytesIO

from django.contrib.auth.hashers import make_password, check_password  # 加密，解密
from django.core.cache import cache
from django.core.mail import send_mail
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.template import loader

from AXF import settings
from UserApp.models import AxfUser
from UserApp.view_helper import sendEmail


def register(request):
    if request.method == 'GET':
        return render(request, 'AXF/user/register/register.html')
    # 注册
    elif request.method == 'POST':
        name = request.POST.get('name')
        password = request.POST.get('password')
        email = request.POST.get('email')
        icon = request.FILES.get('icon')  # 头像 文件

        # check_password()  # 登录的时候解密解密
        password = make_password(password)  # 密码加密

        user = AxfUser()
        user.name = name
        user.password = password
        user.email = email
        user.icon = icon

        token = uuid.uuid4()
        user.token = token

        user.save()

        # 缓存  token为key  user.id为value
        cache.set(token, user.id, timeout=60)  # 设置token存活的时间为60s

        # 发送邮件  以后使用celery异步队列来发送邮件
        # from UserApp.view_helper import sendEmail  # view_helper自己定义的文件，存放发送邮件的
        sendEmail(name, email, token)

        return redirect(reverse('axfuser:login'))


def login(request):
    if request.method == 'GET':
        return render(request, 'AXF/user/login/login.html')
    if request.method == 'POST':
        # 先验证验证码，因为要减少数据库的访问次数
        imgcode = request.POST.get('imgcode')
        # 获取图片中的验证码数字
        verify_code = request.session.get('verify_code')

        if imgcode.lower() == verify_code.lower():
            name = request.POST.get('name')
            users = AxfUser.objects.filter(name=name)
            # print(users)  # 获取到的是<QuerySet [<AxfUser: AxfUser object>]>
            # print(users.first())   # AxfUser object
            if users.exists:
                # 注册的时候，密码首先进行前端加密，才传入视图函数中
                # 然后再视图函数中又进行后端加密（解码的时候，解密为前端加密的密码）

                # 解决方法：在登录的时候，密码也进行前端加密(提高安全性)，然后进行密码比较
                password = request.POST.get('password')

                user = users.first()

                # 没有加密的密码放在前面，加密了的密码放在后面
                if check_password(password, user.password):
                    # 判断账号是否激活
                    if user.active:

                        # session不能直接绑定对象，可以绑定一个对象的属性
                        request.session['user_id'] = user.id
                        request.session['user.name'] = user.name

                        return redirect(reverse('axfmine:mine'))
                    else:
                        context = {
                            'msg': '账号未激活'
                        }
                        return render(request, 'AXF/user/login/login.html', context=context)

                else:
                    context = {
                        'msg': '密码错误'
                    }
                    return render(request, 'AXF/user/login/login.html', context=context)

            else:
                context = {
                    'msg': '该用户名不存在！'
                }
                return render(request, 'AXF/user/login/login.html', context=context)

        else:
            context = {
                'msg': '验证码错误'
            }
            return render(request, 'AXF/user/login/login.html', context=context)



def checkName(request):
    data = {
        'status': 200,
        'msg': '用户名字可以使用'
    }

    name = request.GET.get('name')
    # print(name)
    user = AxfUser.objects.filter(name=name)

    '''
    user = AxfUser.objects.filter(name=name).count()  # 统计user的个数
    if user >= 1:
        data['msg'] = '用户名已经存在'
        data['status'] = 201
        return JsonResponse(data=data)
    else:
        return JsonResponse(data=data)
    '''

    # 获取单个数据：get first lase count exists

    # if user.exists()   如果user存在，返回True  # exists存在量词
    if user.exists():
        data['msg'] = '用户名已经存在'
        data['status'] = 201
        return JsonResponse(data=data)
    else:
        return JsonResponse(data=data)

    return JsonResponse(data=data)


# 测试发送email
def testEmail(request):
    # subject, message, from_email, recipient_list
    # 主题
    subject = '激活'
    # 邮件的内容
    message = '邮件发送可以吗？'

    # 加载
    # from django.template import loader
    index = loader.get_template('AXF/user/register/active.html')
    # 渲染
    context = {
        'name': '顺利',
        'url': 'http://www.baidu.com'
    }
    result = index.render(context=context)
    html_message = result

    # 发送者
    from_email = 'syealfalfa@163.com'
    # 接收者
    recipient_list = ['syealfalfa@163.com']  # 接收者可以是多个人，所有是列表
    # from django.core.mail import send_mail
    send_mail(subject=subject, message=message, html_message=html_message, from_email=from_email,
              recipient_list=recipient_list)

    return HttpResponse('发送邮件成功')


def account(request):
    # 将当前注册的用户的激活状态修改为True
    token = request.GET.get('token')

    user_id = cache.get(token)  # token是key, 获取到的是对象的id

    if user_id:
        user = AxfUser.objects.get(pk=user_id)
        user.active = True

        user.save()

        # 删除缓存的方法没有任何提示，是delete方法  ****************
        cache.delete(token)  # 删除缓存（确保token在有效期内邮箱只能激活一次）

        return HttpResponse('激活成功')
    else:
        return HttpResponse('邮件已过期')

    # 一直激活成功，做测试使用
    # users = AxfUser.objects.filter(token=token)
    # print(type(users))  # <class 'django.db.models.query.QuerySet'>
    # print(users.first())  # AxfUser object

    # if users.count() > 0:
    #     user = users.first()
    #     user.active = True  # 即1
    #
    #     user.save()
    #
    # return HttpResponse('恭喜，您的邮箱已经成功激活！')


# 验证码 （img标签即可以发送请求，又可以接收传递过来的数据并进行处理）
def get_code(request):

    # 初始化画布，初始化画笔

    mode = "RGB"

    size = (200, 100)

    red = get_color()

    green = get_color()

    blue = get_color()

    color_bg = (red, green, blue)

    image = Image.new(mode=mode, size=size, color=color_bg)

    imagedraw = ImageDraw(image, mode=mode)

    # FONT_PATH 验证码的字体
    imagefont = ImageFont.truetype(settings.FONT_PATH, 100)

    verify_code = generate_code()

    # 将生成的验证码绑定到session中
    request.session['verify_code'] = verify_code

    for i in range(4):
        fill = (get_color(), get_color(), get_color())
        imagedraw.text(xy=(50*i, 0), text=verify_code[i], font=imagefont, fill=fill)

    for i in range(500):  # range中的数越大，验证码图片越模糊，可以自定义设置
        fill = (get_color(), get_color(), get_color())
        xy = (random.randrange(201), random.randrange(100))
        imagedraw.point(xy=xy, fill=fill)

    fp = BytesIO()

    image.save(fp, "png")

    return HttpResponse(fp.getvalue(), content_type="image/png")

import random

def get_color():
    return random.randrange(256)

def generate_code():
    source = "qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM"  # 在这些中随机选择4个字符组成验证码
    code = ""
    for i in range(4):
        code += random.choice(source)

    return code


# 退出
def logout(request):
    # 冲刷  删除session和cookie中的脏数据
    request.session.flush()
    return redirect(reverse('axfmine:mine'))